package com.yiban.demo.Global.Controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.yiban.demo.Global.Entity.ResponseEntity;
import com.yiban.demo.Exception.MessageServiceException;
import com.yiban.demo.Global.Exception.MethodArgumentNotLegalException;
import com.yiban.demo.Util.JsonUtil;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingRequestHeaderException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.client.HttpClientErrorException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.stream.Collectors;

@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public void bindExceptionHandle(MethodArgumentNotValidException e,HttpServletResponse httpServletResponse) throws JsonProcessingException {
        final String errorInfo = e.getBindingResult().getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining("\n"));
        ResponseEntity.writeBack(httpServletResponse, JsonUtil.defaultJsonify(ResponseEntity.Failure(errorInfo)));
    }
    @ExceptionHandler({HttpClientErrorException.BadRequest.class, MethodArgumentNotLegalException.class})
    public void badRequestHandle(Exception e,HttpServletResponse httpServletResponse){
        httpServletResponse.setContentType("text/plain; charset=utf-8");
        try(final PrintWriter writer = httpServletResponse.getWriter()) {
            writer.write(JsonUtil.defaultJsonify(ResponseEntity.Failure(e.getMessage())));
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }

    @ExceptionHandler(MissingRequestHeaderException.class)
    public void missingRequestHeaderExceptionHandle(MissingRequestHeaderException e,HttpServletResponse httpServletResponse) throws JsonProcessingException {
        ResponseEntity.writeBack(httpServletResponse, JsonUtil.defaultJsonify(ResponseEntity.Failure("header缺少"+e.getHeaderName())));
    }

    @ExceptionHandler(MessageServiceException.class)
    public void MessageServiceExceptionHandle(MessageServiceException e,HttpServletResponse httpServletResponse) throws JsonProcessingException {
        ResponseEntity.writeBack(httpServletResponse, JsonUtil.defaultJsonify(ResponseEntity.Failure("站点链路异常")));
    }


}
